import configparser
import os
import requests
import random
import time
from loguru import logger

# 读取配置文件
config = configparser.ConfigParser()
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_PATH = os.path.join(BASE_DIR, "config.ini")
config.read(CONFIG_PATH)

# 日志模块
LOG_PATH = os.path.join(BASE_DIR, "log", f'{time.strftime("%Y%m%d%H%M%S")}.log')
logger.remove(handler_id=None)  # 禁用默认控制台输出
logger.add(
    LOG_PATH,
    format="[{time:YYYY-MM-DD HH:mm:ss}] - [{level}] - {message}",
    rotation="500MB",
    encoding="utf-8",
    enqueue=True,
    retention="30 days",
)


# 2s内随机暂停
def random_pause():
    pause_time = random.uniform(0, 2)
    time.sleep(pause_time)


# 获取当前美元转人民币汇率
def get_usd_to_cny_rate():
    exchange_rate = float(config.get("CSFLOAT", "EXCHANGE"))
    try:
        response = requests.get(
            "https://api.exchangerate-api.com/v4/latest/USD",
            timeout=10000,
        ).json()
        usd_to_cny = response["rates"]["CNY"]
        return usd_to_cny
    except:
        logger.warning("汇率请求错误，使用默认汇率！")
        # print("汇率请求错误，使用默认汇率！")
        return exchange_rate


# 获取免费的IP代理池
def get_ip_proxy_list():
    params = {"protocol": "https", "count": "20"}
    res = requests.get(
        "https://proxy.scdn.io/api/get_proxy.php",
        params=params,
        timeout=10000,
    ).json()
    if res.get("code", False) != 200:
        logger.warning("IP代理池获取失败！")
        # print("IP代理池获取失败！")
        return None
    else:
        return res.get("data", {}).get("proxies", [])
